﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AMStudio.UserInterface
{
    public partial class StationConfigUI : Form
    {
        private int stationCfg = 0;

        public int StationCfg
        {
            get { return stationCfg; }
            set { stationCfg = value; }
        }

        public StationConfigUI()
        {
            InitializeComponent();
        }

        public StationConfigUI(int cfg)
            : this()
        {
            stationCfg = cfg;
        }

        private void StationConfigUI_Load(object sender, EventArgs e)
        {
            this.nestTableUI1.HoleClickEventHandler = new EventHandler<Windows.Forms.HoleEventArgs>(nestTableUI1_HoleClickEvent);

            int temp = 0;
            for (int i = 0; i < 6; i++)
            {
                temp = 1 << i;
                if ((stationCfg & temp) > 0)
                    this.nestTableUI1.Status[i] = System.Drawing.Color.Red;
                else
                    this.nestTableUI1.Status[i] = System.Drawing.Color.Green;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool[] status = new bool[6];
            for (int i = 0; i < 6; i++)
            {
                if (this.nestTableUI1.Status[i] == System.Drawing.Color.Red)
                {
                    status[i] = true;
                }
            }
            stationCfg = 0;
            ConvertBooleanArrayToOneWord(status, ref stationCfg);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void nestTableUI1_HoleClickEvent(object sender, Windows.Forms.HoleEventArgs e)
        {
            if (this.nestTableUI1.Status[e.SelectedItem - 1] == System.Drawing.Color.Red)
                this.nestTableUI1.Status[e.SelectedItem - 1] = System.Drawing.Color.Green;
            else
                this.nestTableUI1.Status[e.SelectedItem - 1] = System.Drawing.Color.Red;
            this.nestTableUI1.Invalidate();
        }

        private void ConvertBooleanArrayToOneWord(bool[] data, ref int dest)
        {
            if (data == null)
                return;
            int len = Math.Min(16, data.Length);
            for (int i = 0; i < len; i++)
            {
                if (data[i])
                {
                    dest += (UInt16)(1 << i);
                }
            }
        }

    }
}
